package apj.demo.message.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import apj.demo.util.JDBCUtil;

@WebServlet("/len")
public class PageLenServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		int count = 0;
		try{
			if(request.getParameter("search_type") == null){
				count = getLen(request.getParameter("type"));
			}else{
				count = getVenLen(request.getParameter("search_type"));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		PrintWriter out = response.getWriter();
		out.print(count);
	}
	
	public int getLen(String type) throws Exception{
		int pageCount = 0;
		String sql = "select count(*) as count from " + type;
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rst = null;
		
		try {
			conn = JDBCUtil.getConnection();
			prep = conn.prepareStatement(sql);
			rst = prep.executeQuery();
			
			if(rst.next()){
				pageCount = rst.getInt("count");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			conn.close();
			prep.close();
			rst.close();
		}
		
		return pageCount;
	}
	
	public int getVenLen(String searchTyp) throws Exception{
		int pageCount = 0;
		String sql = "select count(vendor) as count from bill where vendor = '" + searchTyp +"' and bill_finish = 'F'";
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rst = null;
		
		try{
			conn = JDBCUtil.getConnection();
			prep = conn.prepareStatement(sql);
			rst = prep.executeQuery();
			
			if(rst.next()){
				pageCount = rst.getInt("count");
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			conn.close();
			prep.close();
			rst.close();
		}
		
		return pageCount;
	}

}
